/*
 *   Copyright 2021 zzh
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 */

package com.aduib.boot.web.context;

import cn.hutool.core.util.StrUtil;
import com.aduib.boot.common.exception.CommonException;
import com.aduib.boot.common.exception.JwtTokenExpiredException;
import com.aduib.boot.common.exception.ServiceException;
import com.aduib.boot.web.configure.ProfilesProperties;
import com.aduib.boot.web.constants.AppConstants;
import com.aduib.boot.web.context.response.JsonResult;
import com.aduib.boot.web.context.response.ResponseCodeEnum;
import com.aduib.boot.web.exception.DateFormatErrorException;
import com.aduib.boot.web.exception.ReqAndRepsNotFoundException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.Objects;

/**
 * @description: GolbalExceptionHandler
 * @author: zzh
 * @date: 2021/9/6 16:58
 */
@RestControllerAdvice
public class GolbalExceptionHandler {

  private ProfilesProperties profilesProperties;

  private boolean printStackTrace=false;

  public GolbalExceptionHandler(ProfilesProperties profilesProperties) {
    this.profilesProperties = profilesProperties;
    if(StrUtil.isNotBlank(profilesProperties.getActive())&&(profilesProperties.getActive().contains(
        AppConstants.DEV_PROFILE)||profilesProperties.getActive().contains(
        AppConstants.TEST_PROFILE) )){
      printStackTrace=true;
    }
  }

  @ExceptionHandler(value= ServiceException.class)
  public JsonResult handleServiceException(ServiceException exception){
    printStackTrace(exception);
    return createJsonResult(exception.getCode(),exception.getMessage());
  }

  @ExceptionHandler(value= JwtTokenExpiredException.class)
  public JsonResult handleJwtTokenExpiredException(JwtTokenExpiredException exception){
    printStackTrace(exception);
    return JsonResult.unauthorized(exception.getMessage());
  }

  @ExceptionHandler(value= CommonException.class)
  public JsonResult handleCommonException(CommonException exception){
    printStackTrace(exception);
    return createJsonResult(null,exception.getMessage());
  }

  @ExceptionHandler(value= DateFormatErrorException.class)
  public JsonResult handleDateFormatErrorException(DateFormatErrorException exception){
    printStackTrace(exception);
    return createJsonResult(null,exception.getMessage());
  }

  @ExceptionHandler(value= ReqAndRepsNotFoundException.class)
  public JsonResult handleReqAndRepsNotFoundException(ReqAndRepsNotFoundException exception){
    printStackTrace(exception);
    return createJsonResult(null,exception.getMessage());
  }

  @ExceptionHandler(MethodArgumentNotValidException.class)
  public JsonResult handle(MethodArgumentNotValidException e) {
    BindingResult result = e.getBindingResult();
    StringBuilder errorMsg = new StringBuilder();
    if (result.hasErrors()) {
      List<FieldError> fieldErrors = result.getFieldErrors();
      fieldErrors.forEach(error -> {
        errorMsg.append(error.getDefaultMessage()).append("!");
      });
    }
    return createJsonResult(ResponseCodeEnum.ILLEGAL_ARGUMENT_EXCEPTION.getCode(), "【" + ResponseCodeEnum.ILLEGAL_ARGUMENT_EXCEPTION.getMessage() + "】" + errorMsg.toString());
  }

  /**
   * 拦截所有异常
   * @param exception
   * @return
   */
  @ExceptionHandler(value= Exception.class)
  public JsonResult handleException(Exception exception){
    printStackTrace(exception);
    return createJsonResult(ResponseCodeEnum.SYS_EXCEPTION.getCode(),exception.getMessage());
  }

  /**
   * 打印异常
   * @param e
   */
  public void printStackTrace(Exception e){
    if(printStackTrace){
      e.printStackTrace();
    }
  }

  /**
   * 创建返回对象
   * @param code
   * @param message
   * @return
   */
  public JsonResult createJsonResult(Integer code,String message){
    if(Objects.isNull(code)){
      return JsonResult.failure(message);
    }else{
      return JsonResult.failure(code,message);
    }
  }
}
